<template>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="formRef sign-in-form">
        <el-form-item label="账号" prop="username" class="mt-5">
            <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="verifycode" label="验证码">
        <!-- 注意：prop与input绑定的值一定要一致，否则验证规则中的value会报undefined，因为value即为绑定的input输入值 -->
        <el-input v-model="form.verifycode" placeholder="请输入验证码" class="identifyinput"></el-input>
        </el-form-item>
        <el-form-item>
        <div class="identifybox">
        <div @click="refreshCode">
            <s-identify :identifyCode="identifyCode"></s-identify>
        </div>
        <el-button @click="refreshCode" type='text' class="textbtn">看不清，换一张</el-button>
        </div>
        </el-form-item>
        <el-form-item>
            <el-button @click="onSubmit" type="primary" class="submit-btn">提交
            </el-button>
        </el-form-item>

        <!-- 找回密码 -->
        <!--        <div class="tiparea">-->
        <!--            <p>忘记密码？ <a>立即找回</a></p>-->
        <!--        </div>-->
    </el-form>
</template>

<script setup>
import { ref, getCurrentInstance, reactive, onMounted, onBeforeUnmount } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { toast } from "~/composables/util.js";

import SIdentify from '~/components/Captcha.vue'

const store = useStore();
const router = useRouter();
const identifyCodes = ref("1234567890") //验证码的数字库
const identifyCode = ref('')  // 验证码组件传值


//验证码----start
const randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min);
}
const refreshCode = () => {
    identifyCode.value = "";
    makeCode(identifyCodes.value, 4);
}
const makeCode = (o, l) => {
    for (let i = 0; i < l; i++) {
        identifyCode.value += identifyCodes.value[
            randomNum(0, identifyCodes.value.length)
        ];
    }
    // console.log("this.identifyCode:", this.identifyCode);
}
//验证码----end


const form = reactive({
    username: "",
    password: "",
    verifycode: '',

});
// 验证码自定义验证规则
const validateVerifycode = (rule, value, callback) => {
  if (value === '') {
  callback(new Error('请输入验证码'))
  } else if (value !== identifyCode.value) {
  console.log('validateVerifycode:', value)
  callback(new Error('验证码不正确!'))
  } else {
  callback()
  }
 }
const rules = {
    username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    password: [
        { required: true, message: "密码不能为空", trigger: "blur" },
        { min: 5, max: 15, message: "密码长度为5~15个字符", trigger: "blur" },
    ],
    verifycode: [
   { required: true, trigger: 'blur', validator: validateVerifycode }
  ]
};
const formRef = ref(null);
const loading = ref(false);

const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return false;
        }
        loading.value = true;
        store.dispatch("postUserLogin", form)
            .then((res) => {
                toast("登录成功")
                // 直接请求用户数据
                store.dispatch("getUserInfo").then().finally(() => {
                    loading.value = false
                    router.push("/")
                })
            })
            .catch((error) => {
            });
    });
};

// 监听回车事件
function onKeyUp(e) {
    if (e.key == "Enter") {
        onSubmit();
    }
}

// 键盘事件
onMounted(() => {
    document.addEventListener("keyup", onKeyUp);


    refreshCode(); //初始化验证码

     // 验证码初始化
    identifyCode.value = '';
    makeCode(identifyCodes.value, 4);
});
onBeforeUnmount(() => {
    document.removeEventListener("keyup", onKeyUp);
});

// defineProps({
//     loginUser: Object,
// });
</script>
<style scoped>
/* form */
.formRef {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px 40px 20px 20px;
    border-radius: 5px;
    box-shadow: 0px 5px 10px #cccc;
}

.submit-btn {
    width: 100%;
}

.tiparea {
    text-align: right;
    font-size: 12px;
    color: #333;
}

.tiparea p a {
    color: #409eff;
}
</style>